package com.blb.seckill.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;

/**
 * RabbitMQ的配置
 */
@Slf4j
@Configuration
public class RabbitMQConfig {

    public static final String MESSAGE_CONFIRM = "message-confirm-";
    public static final String QUEUE_SECKILLORDER = "queue.seckillorder";

    @Bean
    public Queue queueCourse() {
        //持久化队列
        return new Queue(QUEUE_SECKILLORDER,true);
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack) {
                    log.info("消息{}发送到Exchange成功!!!",correlationData);
                    redisTemplate.delete(correlationData.getId());
                    redisTemplate.delete(MESSAGE_CONFIRM + correlationData.getId());
                } else {
                    log.error("消息{}发送到Exchange失败,原因：{}",correlationData,cause);
                    //返回失败通知
                    Map<String,String> map =(Map<String,String>)redisTemplate.opsForHash().entries(MESSAGE_CONFIRM +correlationData.getId());
                    String exchange = map.get("exchange");
                    String routingKey = map.get("routingKey");
                    String sendMessage = map.get("sendMessage");
                    //重新发送
                    rabbitTemplate.convertAndSend(exchange,routingKey, JSON.toJSONString(sendMessage));
                }
            }
        });
        return rabbitTemplate;
    }
}
